//
//  DDBossSetPositionViewController.m
//  DingDongZP
//
//  Created by Ray on 16/4/22.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDBossSetPositionViewController.h"
#import <HMSegmentedControl/HMSegmentedControl.h>
#import "DDBossTagCell.h"
#import "DDPositionFootView.h"
#import "DDBossInfoService.h"

@interface DDBossSetPositionViewController ()
<UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) HMSegmentedControl *segmentedControl;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) DDBossInfoService *service;

@property (nonatomic, strong) NSArray *positionCates;
@property (nonatomic, strong) NSDictionary *positions;

@property (nonatomic, copy) NSString *selectPositionId;


@end

@implementation DDBossSetPositionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.segmentedControl];
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    ///
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 20, 20);
    layout.footerReferenceSize = CGSizeMake(self.view.frame.size.width, 90);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = COLOR_BACKGROUND;
    [self.view addSubview:_collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.segmentedControl.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"DDBossTagCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"DDPositionFootView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];
    
    /// 大小按屏幕大小来计算
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 40 - 10*2) / 3.0, 40);
    
    self.navigationItem.rightBarButtonItem = self.confirmItem;
    
    [self loadPositions];
}

- (HMSegmentedControl *)segmentedControl
{
    if (!_segmentedControl) {
        _segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"公司BOSS", @"部门BOSS", @"人事HR"]];
        _segmentedControl.backgroundColor = [UIColor whiteColor];
        _segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName:COLOR_FONT_DARK_GRAY,NSFontAttributeName:[UIFont systemFontOfSize:15]};
        _segmentedControl.selectionIndicatorHeight = 2.f;
        _segmentedControl.selectionIndicatorColor = COLOR_NAVIGATIONBAR;
        _segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
        
        [_segmentedControl setIndexChangeBlock:^(NSInteger index) {
            
        }];
        _segmentedControl.layer.shadowColor = COLOR_BORDER_GRAY.CGColor;
        _segmentedControl.layer.shadowOffset = CGSizeMake(0.0f, 3.0f);
        _segmentedControl.frame = CGRectMake(0, 0, SCREEN_WIDTH - 50, 40);
        [_segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    }
    return _segmentedControl;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - segger/getter
- (DDBossInfoService *)service {
    if (!_service) {
        _service = [[DDBossInfoService alloc] init];
    }
    return _service;
}

#pragma mark - functions
- (void)loadPositions
{
    WEAKSELF
    [self showLoading];
    [self.service queryEmployerPositions:^(NSArray *positions) {
        [weakSelf hideLoading];
        [weakSelf updateWithPositions:positions];
    }];
}

- (void)updateWithPositions:(NSArray *)positions
{
    NSMutableArray *cates = [NSMutableArray new];
    NSMutableDictionary *newpositions = [NSMutableDictionary new];
    for (DDBossPosition *p in positions) {
        NSMutableArray *catearray = [newpositions objectForKey:p.category_name];
        if (!catearray) {
            catearray = [NSMutableArray new];
            [newpositions setObject:catearray forKey:p.category_name];
            [cates addObject:p.category_name];
        }
        
        [catearray addObject:p];
        
        /// 判断选中项
        if ([p.position_name isEqualToString:self.positionName]) {
            self.selectPositionId = p.position_id;
        }
    }
    
    /// 如果有position但没有custompositionname，则赋值
    if (!self.positionCustomName && self.positionName) {
        self.positionCustomName = self.positionName;
    }
    
    self.positionCates = cates;
    self.positions = newpositions;
    [self.segmentedControl setSectionTitles:self.positionCates];
    [self.collectionView reloadData];
}

- (void)segmentedControlChangedValue:(HMSegmentedControl *)seg
{
    [self.collectionView reloadData];
}

- (void)actionConfirm:(UIButton *)btn
{
    if (self.didSelectPosition) {
        self.didSelectPosition(self.selectPositionId, self.positionCustomName);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSArray *)displayingPositions
{
    if (_segmentedControl.selectedSegmentIndex < self.positionCates.count) {
        NSString *cate = self.positionCates[_segmentedControl.selectedSegmentIndex];
        NSArray *positions = self.positions[cate];
        return positions;
        
    }
    return nil;
}

#pragma mark - delegates
#pragma mark -- collection view

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self displayingPositions].count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDBossTagCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    NSArray *positions = [self displayingPositions];
    DDBossPosition *p = positions[indexPath.row];
    cell.nameLab.text = p.position_name;
    if ([p.position_id isEqualToString:self.selectPositionId]) {
        cell.selected = YES;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *positions = [self displayingPositions];
    DDBossPosition *p = positions[indexPath.row];
    self.positionCustomName = p.position_name;
    self.selectPositionId = p.position_id;
    [self.collectionView reloadData];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionFooter])
    {
        DDPositionFootView *foot = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"foot" forIndexPath:indexPath];
        foot.positionShow.text = self.positionCustomName;
        WEAKSELF
        foot.didGetValue = ^(NSString *value) {
            weakSelf.positionCustomName = value;
        };
        return foot;
    }
    return nil;
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
